﻿using Microsoft.EntityFrameworkCore;
using Sgr.DataCategories.Domain.DataCategoryItem;
using Sgr.Domain.Entities;
using Sgr.Domain.Entities.Auditing;
using Sgr.Domain.Repositories;
using Sgr.EntityFrameworkCore;
using Sgr.Exceptions;
using Sgr.Generator;
using Sgr.Generator.Segment;

namespace Sgr.DataCategories.Infrastructure.Repositories
{
    /// <summary>
    /// 数据字典项仓储实现
    /// </summary>
    public class DataCategoryItemRepository<TDbContext> :
         EfCoreTreeNodeBaseRepositoryOfTEntityAndTPrimaryKey<TDbContext, DataCategoryItem, long>, IDataCategoryItemRepository where TDbContext : UnitOfWorkDbContext
    {
        private readonly ISegmentNumIdGenerator _numberIdGenerator;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContextProvider"></param>
        /// <param name="auditedOperator">审计操作者</param>
        /// <param name="numberIdGenerator">数字ID生成器</param>
        /// <exception cref="BusinessException">参数为空时抛出异常</exception>
        public DataCategoryItemRepository(
            IDbContextProvider<TDbContext> dbContextProvider,
            IAuditedOperator auditedOperator,
            ISegmentNumIdGenerator numberIdGenerator)
            : base(dbContextProvider, auditedOperator)
        {
            _numberIdGenerator = numberIdGenerator ?? throw new ArgumentNullException(nameof(numberIdGenerator));
        }

        /// <summary>
        /// 检查并设置主键Id
        /// </summary>
        /// <param name="entity">实体</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns></returns>
        protected override async Task CheckAndSetIdAsync(DataCategoryItem entity, CancellationToken cancellationToken = default)
        {
            if (entity.Id == 0)
                entity.Id = await _numberIdGenerator.GetUniqueIdAsync(SegmentNumIdGenerator.DEFAULT_KEY, cancellationToken);
        }

        /// <summary>
        /// 检查特定类型下的数据字典值是否唯一
        /// </summary>
        /// <param name="value">字典项值</param>
        /// <param name="categoryTypeCode">字典分类编码</param>
        /// <param name="excludeId">需要排除的ID</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>true: 值已存在; false: 值不存在</returns>
        /// <exception cref="ArgumentNullException">当必要参数为空时抛出</exception>
        public async Task<bool> ValueIsUniqueInCategoryAsync(
            string value,
            string categoryTypeCode,
            long? excludeId = null,
            CancellationToken cancellationToken = default)
        {
            // 参数验证
            Check.StringNotNullOrEmpty(value, nameof(value));
            Check.StringNotNullOrEmpty(categoryTypeCode, nameof(categoryTypeCode));

            // 构建查询条件
            var dbContext = await GetDbContextAsync(cancellationToken);
            var query = dbContext.Set<DataCategoryItem>()
                .AsNoTracking()
                .Where(x => x.CategoryTypeCode == categoryTypeCode
                           && x.DcItemValue == value);

            // 排除指定ID的记录
            if (excludeId.HasValue && excludeId.Value > 0)
            {
                query = query.Where(x => x.Id != excludeId.Value);
            }

            return !await query.AnyAsync(cancellationToken);
        }

        /// <summary>
        /// 根据字典分类编码获取字典项列表
        /// </summary>
        /// <param name="categoryTypeCode">字典分类编码</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>字典项列表</returns>
        public async Task<IEnumerable<DataCategoryItem>> GetByCategoryTypeCodeAsync(string categoryTypeCode, CancellationToken cancellationToken = default)
        {
            var dbContext = await GetDbContextAsync(cancellationToken);
            return await dbContext.Set<DataCategoryItem>()
                .Where(f => f.CategoryTypeCode == categoryTypeCode)
                .Where(f => f.State == EntityStates.Normal)
                .OrderBy(f => f.OrderNumber)
                .ToListAsync(cancellationToken);
        }
    }
}